﻿namespace USElections.Analytics
{
    using System.ComponentModel.Composition.Hosting;
    using System.Windows;
    using Google.WebAnalytics;
    using Microsoft.WebAnalytics;
    using Microsoft.WebAnalytics.Data;

    /// <summary>
    /// AnalyticsService class.
    /// </summary>
    public class AnalyticsService : IApplicationService
    {
        #region Fields
        private readonly IApplicationService service;
        private readonly GoogleAnalytics googleAnalytics;
        #endregion

        #region Constructor
        /// <summary>
        /// Initializes a new instance of the AnalyticsService class.
        /// </summary>
        public AnalyticsService()
        {
            this.googleAnalytics = new GoogleAnalytics();
            this.googleAnalytics.CustomVariables.Add(new PropertyValue { PropertyName = "AppVersion", Value = AnalyticsProperties.ApplicationVersion });
            this.googleAnalytics.CustomVariables.Add(new PropertyValue { PropertyName = "ANID", Value = AnalyticsProperties.ANID });

            this.service = new WebAnalyticsService
            {
                Services = { this.googleAnalytics, }
            };
        }
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the WebPropertyId for the Google Analytics.
        /// </summary>
        public string WebPropertyId
        {
            get { return this.googleAnalytics.WebPropertyId; }
            set { this.googleAnalytics.WebPropertyId = value; }
        }
        #endregion

        #region Public methods
        /// <summary>
        /// Start the Application Service.
        /// </summary>
        /// <param name="context">The ApplicationService context.</param>
        public void StartService(ApplicationServiceContext context)
        {
            CompositionHost.Initialize(
                new AssemblyCatalog(Application.Current.GetType().Assembly),
                new AssemblyCatalog(typeof(Microsoft.WebAnalytics.AnalyticsEvent).Assembly),
                new AssemblyCatalog(typeof(Microsoft.WebAnalytics.Behaviors.TrackAction).Assembly),
                new AssemblyCatalog(typeof(Microsoft.WebAnalytics.Controls.HandlePanorama).Assembly));

            this.service.StartService(context);
        }

        /// <summary>
        /// Stop the Application service.
        /// </summary>
        public void StopService()
        {
            this.service.StopService();
        }
        #endregion
    }
}
